<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\WeappAuthorizationRequest;
use App\Models\User;
use App\Http\Resources\UserResource;

class AuthorizationsController extends Controller
{
    public function weappStore(WeappAuthorizationRequest $request)
    {
        $code = $request->code;
        //本地环境直接模拟用户授权
        if (app()->environment('local')) {
            $data = [
                "session_key" => "YiNglxrseQLJhPvUOOz+IQ==",
                "openid" => "oP91d1EPDbt1wljf3vNUxsMasOcA"
            ];
        } else {
            // 根据 code 获取微信 openid 和 session_key
            $miniApp = app('easywechat.mini_app');
            $utils = $miniApp->getUtils();
            $data = $utils->codeToSession($code);
        }

        // 如果结果错误，说明 code 已过期或不正确，返回 401 错误
        if (isset($data['errcode'])) {
            return $this->failed('weixin-app-code-error');
        }

        // 找到 openid 对应的用户
        $user = User::where('weapp_openid', $data['openid'])->first();

        if ($user) {
            $attributes['weixin_session_key'] = $data['session_key'];
            // 更新用户数据
            $user->update($attributes);
        } else {
            $attributes = [
                'weixin_unionid' => isset($data['unionid']) ? $data['unionid'] : '',
                'weapp_openid' => $data['openid'],
                'weixin_session_key' => $data['session_key'],
            ];

            // 创建用户
            $user = User::create($attributes);
        }

        $user->tokens()->delete();
        $token = $user->createToken('api', ['api:all'])->plainTextToken;
        $data = [
            'access_token' => $token
        ];
        return $this->success($data);
    }

    public function getPhoneNumber(WeappAuthorizationRequest $request)
    {
        $miniApp = app('easywechat.mini_app');
        $data = [
            'code' => $request->code
        ];

        $data = $miniApp->getClient()->postJson('wxa/business/getuserphonenumber', $data);
        if (!isset($data['errcode']) && $data['errcode'] != 0) {
            return $this->failed('weixin-get-user-phone-number-code-error');
        }

        $user = $request->user();
        $user->phone = $data['phone_info']['purePhoneNumber'];
        $user->save();
        return $this->resource(new UserResource($user));
    }
}
